import { isString, isNumber, isUnDef, isNullOrEmpty, isObject } from '@/utils/is';
import dayjs from 'dayjs';

// 属性格式化-Number
export function propertyFormatByNumber(value, params) {
  // 只处理基础类型
  if (isString(value) || isNumber(value)) {
    // 分为整数部分与小数部分
    let [integerPart, decimalPart] = String(value).split('.');
    const { decimal, accuracy, thousandthSeparator, currencySymbol } = params;
    // 处理千分位
    if (thousandthSeparator) {
      // 兼容千分位，将已有的千分位移除
      integerPart.replace(',', '');
      // 使用正则处理千分位
      integerPart = integerPart.replace(/\d{1,3}(?=(\d{3})+$)/g, (match) => {
        return match + ',';
      });
    }
    // 处理小数
    if (accuracy > 0) {
      decimalPart = isUnDef(decimalPart) ? '0' : decimalPart;
      // 分割并向后补零
      decimalPart = decimalPart.slice(0, accuracy).padEnd(accuracy, '0');
    }
    return `${currencySymbol ? currencySymbol : ''}${integerPart}${
        accuracy > 0 ? decimal + decimalPart : ''
    }`;
  }
  return value;
}

// 属性格式化-Percentage 百分比
export function propertyFormatByPercentage(value, params) {
  if (isString(value) || isNumber(value)) {
    // 分为整数部分与小数部分
    let [integerPart, decimalPart] = String(accMul(value, 100)).split('.');
    const { decimal, accuracy } = params;
    // 处理小数
    if (accuracy > 0) {
      decimalPart = isUnDef(decimalPart) ? '0' : decimalPart;
      // 分割并向后补零
      decimalPart = decimalPart.slice(0, accuracy).padEnd(accuracy, '0');
    }
    return `${integerPart}${accuracy > 0 ? decimal + decimalPart : ''}%`;
  }
  return value;
}

// 属性格式化-DATE
export function propertyFormatByDate(value, params) {
  try {
    const { dateFormat } = params;
    return dayjs(value).format(dateFormat);
  } catch (error) {
    console.log('error format date ', error);
    return value;
  }
}

/**
 * 乘法
 * @param arg1
 * @param arg2
 * @returns {number}
 */
export function accMul(arg1, arg2) {
  let m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split('.')[1].length;
  } catch (e) {}
  try {
    m += s2.split('.')[1].length;
  } catch (e) {}
  return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m);
}

/**
 * 除法
 * @param val
 * @param valTwo
 * @returns {number}
 */
export function exc(val, valTwo = 100) {
  if (isNullOrEmpty(val)) {
    return undefined;
  }
  const strVal = val.toString();
  const strValTwo = valTwo.toString();
  const index = strVal.indexOf('.');
  const indexTwo = strValTwo.indexOf('.');
  const num = [0, 0];
  if (index > -1) {
    num[0] = strVal.length - 1 - index;
  }
  if (indexTwo > -1) {
    num[1] = strValTwo.length - 1 - index;
  }
  return (
    Math.round(val * Math.pow(10, num[0])) /
    (Math.round(valTwo * Math.pow(10, num[1])) * Math.pow(10, num[0] - num[1]))
  );
}

// 展开零代码表格生成的带有子表单的数据
export function parseSubFromDataList(dataList = []) {
  const newDataList = [];
  let count = 0;
  for (let i = 0, len = dataList.length; i < len; i++) {
    const item = dataList[i];
    const subListArrange: any[] = [];
    const subLen = [];
    for (let k in item) {
      const subList = item[k];
      if (isObject(subList) && 'dataList' in subList && 'columnList' in subList) {
        subListArrange.push({ ...subList, _key: k });
        subLen.push((subList.dataList || []).length);
      }
    }
    if (subListArrange.length) {
      const subMax = Math.max(...subLen);
      const itemStr = JSON.stringify(item);
      for (let n = 0; n < subMax; n++) {
        const itemObj = JSON.parse(itemStr);
        for (let j = 0, len1 = subListArrange.length; j < len1; j++) {
          const _columnList = subListArrange[j].columnList || [];
          const _dataList = subListArrange[j].dataList || [];
          const _key = subListArrange[j]._key;
          const _d = _dataList[n] || {};
          for (let j1 = 0, lenj1 = _columnList.length; j1 < lenj1; j1++) {
            if (!_columnList[j1]['sourceColumnKey']) {
              const key = _columnList[j1].key;
              itemObj[`${_key}_$_${key}`] = _d[key] || '';
            }
          }
          itemObj[`_id`] = count++;
          itemObj[`__SUB_INDEX`] = n;
        }
        newDataList.push(itemObj);
      }
    } else {
      item[`_id`] = count++;
      newDataList.push(item);
    }
  }
  return newDataList;
}
